package com.gl.mobile.activities;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;

import com.gl.mobile.R;
import com.gl.mobile.constants.Constants;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;

public class CustomListViewActivity extends ListActivity {
    /** Called when the activity is first created. */
	
    static final ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String,String>>();
    
    private JSONArray libros_array;
    
    private String jsonLibros;
    
    private EditText searchText;
    
    private SimpleAdapter adapter;
    
    private Button filtrarBtn;
    
    private ArrayList<Integer> selectedCategories;
	
	@Override
    public void onCreate(Bundle savedInstanceState) 
	{
        super.onCreate(savedInstanceState);

        setContentView(R.layout.content);
        Bundle bundle = getIntent().getExtras();
        if(bundle!=null)
        {
	        if( bundle.containsKey("categories") )
	        	selectedCategories = bundle.getIntegerArrayList("categories");
        }
        
        
        filtrarBtn = (Button) findViewById( R.id.filtrar_btn );
        filtrarBtn.setOnClickListener( new View.OnClickListener() 
        {
        	public void onClick(View v) 
        	{
        		Intent intent = new Intent( getApplicationContext(), FiltrarLibrosActivity.class );
        		Bundle filtroBundle = new Bundle();
        		if( selectedCategories != null )
        			filtroBundle.putIntegerArrayList("selectedCategories", selectedCategories);
        		intent.putExtras(filtroBundle);
        			
        		startActivity(intent);
            }
        	
        });
        
        searchText = (EditText) findViewById( R.id.content_search_text);
        adapter = new SimpleAdapter( this, 
        		list, 
        		R.layout.custom_row_view, 
        		new String[] {"nombre","autor"},
        		new int[] {R.id.text1,R.id.text2} );
        loadLibros();
        setListAdapter(adapter);

        searchText.addTextChangedListener(new TextWatcher() 
        {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count)  
			{
					
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) 
			{
				
			}
			
			@Override
			public void afterTextChanged(Editable s) 
			{
				filtrarTexto( s );
			}
		});
			
     
    }
	
	private void loadLibros()
	{
		new Thread(new Runnable()
        {
	        @Override
	        public void run() 
	        {
	        	String URL = Constants.BASE_PATH + "/rest/listarLibros/";
	            String result = new String();
	            
	        	HttpClient httpclient = new DefaultHttpClient();  
	            HttpGet request = new HttpGet(URL);  
	            ResponseHandler<String> handler = new BasicResponseHandler();
	            	            
	            try {  
	                result = httpclient.execute(request, handler);  
	            } catch (ClientProtocolException e) {  
	                e.printStackTrace();  
	            } catch (IOException e) {  
	                e.printStackTrace();  
	            }  
	            httpclient.getConnectionManager().shutdown();
	            
	            try {
	    			fillList( result );
	    			jsonLibros = result;
	    		} catch (JSONException e) {
	    			e.printStackTrace();
	    		}
	        }
        }).run();
	}
	
	private void filtrarTexto( Editable s )
	{
		try {
			fillList( jsonLibros );
		} catch (JSONException e) {
			e.printStackTrace();
		}
		
		setListAdapter(adapter);
	}
	
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {

	    super.onListItemClick(l, v, position, id);
	    
	    @SuppressWarnings("unchecked")
		HashMap<String,String> libroSeleccionado = (HashMap<String,String>) this.getListAdapter().getItem(position);
	    
	    Intent intent = new Intent( getApplicationContext(), DetalleLibroActivity.class );
	    Bundle bundle = new Bundle();
	    
	    bundle.putString( "nombre", libroSeleccionado.get("nombre") );
	    bundle.putString( "autor", libroSeleccionado.get("autor") );
	    bundle.putString( "puntuacion", libroSeleccionado.get("puntuacion") );
	    bundle.putString( "idioma", libroSeleccionado.get("idioma") );
	    bundle.putString( "editorial", libroSeleccionado.get("editorial") );
	    bundle.putString( "imagen", libroSeleccionado.get("imagen") );
	    
	    intent.putExtras( bundle );
	    
		startActivity( intent );
	}
	
	private void fillList( String response ) throws JSONException
	{
		list.clear();
		libros_array = new JSONArray(response);
		
		for (int i = 0; i < libros_array.length(); i++) 
		{
			if( libros_array.getJSONObject(i).getString("nombre").toLowerCase().indexOf(searchText.getText().toString()) != -1 )
			{
				if( selectedCategories != null )
				{
					Boolean categorySelected = false;
					for( int j=0; j<selectedCategories.size(); j++ )
					{
						if( selectedCategories.get(j) == Integer.valueOf(libros_array.getJSONObject(i).getInt("categoriaId")) )
							categorySelected = true;
					}
					if( !categorySelected )
						continue;
				}
				HashMap<String,String> temp = new HashMap<String,String>();
				temp.put( "nombre", libros_array.getJSONObject(i).getString("nombre") );
		        temp.put( "autor", libros_array.getJSONObject(i).getString("autor") );
		        temp.put( "id", Integer.toString(libros_array.getJSONObject(i).getInt("id")) );
		        temp.put( "puntuacion", Integer.toString(libros_array.getJSONObject(i).getInt("puntuacion")) );
		        temp.put( "editorial", libros_array.getJSONObject(i).getString("editorial") );
		        temp.put( "idioma", libros_array.getJSONObject(i).getString("idioma") );
		        temp.put( "imagen", libros_array.getJSONObject(i).getString("imagen") );
		        
		        list.add( temp );
			}
		}
	}
	
}